<?php
/* OpenBIBLIO -- A library administration web interface
 * Copyright (C) 2011-     Laurent Luyssen   <big.lol13@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
session_start();
include_once("includes/header.inc");
include_once("includes/db.inc");
include_once("includes/functions.inc");
include_once("includes/session.inc");

$user_id = '';
ControleAcces("admin.php",'','',$user_id,session_id());

function insert_book($author, $title, $genre_id, $location_id, $import_id = '') {
  $date_in = date("Y-m-d"); 
  $liv_coll = '';
  $liv_etat_id = 1;
  $liv_ed = '';
  $liv_date = '';
  $liv_ISBN = '';
  $temp = 0;
  $noout = 0;
  $resume = '';
  $motclefs = '';
  $liv_num = '';
  
  $requete = "INSERT INTO livres (nom, auteur, collection, genre_ID, etat_ID, location_ID, edition, date_ed, ISBN, temp, noout, date_in, resume, motclefs, num, import_ID) values (\"$title\",\"$author\",\"$liv_coll\",\"$genre_id\",\"$liv_etat_id\",\"$location_id\",\"$liv_ed\",\"$liv_date\",\"$liv_ISBN\",$temp,$noout,\"$date_in\",\"$resume\",\"$motclefs\",\"$liv_num\",\"$import_id\")";

  //  echo $requete . "</BR>";

  if(!biblio_db_query($requete)) {
    echo $requete . "</BR>";
    echo _("PROBLEME :").biblio_db_error()."</BR>";
    return false;
  }
  else 
    return true;
}

function processFile($path, $insert = false) {
  $first_name = '';
  $name       = '';
  $title      = '';
  $failed     = array();
  $new_genres = array();
  $new_locations = array();
  
  $import_id = time();
  $rc = array( 'OK' => 0, 'FAIL' => 0);
  
  echo '<table>';
  $fh = fopen($path, 'r');
  while($theData = fgets($fh)) {
  	$genre_id = false;
  	$location_id = false;
  	
    $data = explode(";", $theData);
    if (count($data) < 3) {
      $failed[] = $theData;
      continue;
    }
    // Author name
    $d0 = trim($data[0]);
    if ($d0 != "") {
      // If name has changed, reset first name
      if ($name != $d0) {
        $first_name = "";
        $name = $d0;
      }
    }
    // optionnal first name
    $d1 = trim($data[1]);
    if ($d1 != "")
      $first_name = $d1;
    // title
    $title = trim($data[2]);
    
    if (count($data) > 3) {
    	$editor = trim($data[3]);
    }
	if (count($data) > 4) {
    	$genre = trim($data[4]);
    	$genres = get_genres("where genre = '".$genre."'");
    	if ($genres) {
    		foreach ($genres as $genre_id => $value);
    	}
    	else {
    		if (!in_array($genre, $new_genres) && ($genre != '') )
	    		$new_genres[] = $genre;
    		if ($insert) {
					$genre_id = add_genre($genre);
					if ($genre_id)
						echo _("Genre : ").$genre._(" ajout&eacute; avec id=").$genre_id."</BR>"; 
				}
    	}		
    }

	if (count($data) > 5) {
    	$location = trim($data[5]);
    	$locations = get_locations(" where local='".$location."' ");
    	if ($locations) {
    		foreach ($locations as $location_id => $value);
    	}
    	else {
    		if (!in_array($location, $new_locations) && ($location != '') )
    			$new_locations[] = $location;
    		if ($insert) {
					$location_id = add_location($location);
					if ($location_id)
						echo _("Emplacement : ").$location._(" ajout&eacute; avec id=").$location_id."</BR>";
				}
			}
	}
    // name and title are mandatory
    //|| ($title == "\n") || ($title == "\r") || ($title == "\r\n") 
    if ( ($name == '') || ($title == '') ) {
      $failed[] = $theData;
      continue;
    }
    if ($insert) {
      $author = $name;
      if ($first_name != '')
        $author .= ", ".$first_name;
      if (!$genre_id)
      	$genre_id = $_POST['liv_genre_id'];
      if (!$location_id)
      	$location_id = $_POST['liv_location_id'];
      if (insert_book($author, $title, $genre_id, $location_id, $import_id))
        $rc['OK']++;
      else {
        $rc['FAIL']++;
        $failed[] = $theData; 
      }      
    }
    else {
      echo "<tr><td>".$name."</td><td>".$first_name."</td><td>".$title."</td>";
      echo "<td>$genre($genre_id)</td><td>$location($location_id)</td></tr>";
    }

  }
  fclose($fh);
  echo "</table>";   
  
  echo "</BR><b>"._("Resultats")." :</b></BR>";
  echo $rc['OK']._(" OK")."</BR>";
  echo $rc['FAIL']._(" erreurs")."</BR>";
  if (count($failed) > 0) {
	  echo "</BR><b>"._("Erreurs")."</b></br>";   
	  foreach ($failed as $f)
			echo $f."</br>";
	}
	if (count($new_genres) > 0) {
		echo "</BR><b>"._("Nouveaux genres")."</b></br>";
		foreach ($new_genres as $g)
			echo $g."</br>";
	}
	if (count($new_locations) > 0) {
		echo "</BR><b>"._("Nouveaux emplacements")."</b></br>";
		foreach ($new_locations as $l)
			echo $l."</br>";
	}
}

$uploaddir = 'upload/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if (!isset($_FILES['userfile']['name']) && !isset($_POST['path']) ) {
?>
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
  <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
  <?php echo _("Fichier"); ?> : <input name="userfile" type="file" />
  <?php echo '<input type="submit" value="'._("Envoyer le fichier").'" />' ?>
</form>
</body>
</html>

<?php
}

if (isset($_FILES['userfile']['name'])) {

  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  ?>
  <form action="upload.php" method="post">
    <input type="hidden" name="path" value=<?php echo '"'.$uploadfile.'"'; ?> />
    <table><tr><td>
    
<?php echo _("Genre"); ?>
	:</td><td><select NAME = "liv_genre_id">
<?php
    $genres = get_genres();
    if ($genres) {
      foreach ($genres as $id => $value) {
        print "<option VALUE=\"$id\">$value</option>";
      }
    }
?>
    </select></td></tr>
    <tr><td>
    <?php echo _("Emplacement"); ?>
    :</td><td><select NAME = "liv_location_id">
<?php
    $locations = get_locations();
    if ($locations) {
      foreach ($locations as $id => $value)
        print "<option VALUE=\"$id\">$value</option>";
    }
?>   
    </td></tr>
    <tr><td>
<?php
    echo '<input type="submit" value="'._("Confirmer").'" />';
?>
    </td></form>
    <td><form action="upload.php" method="get">
<?php
    echo '<input type="submit" value="'._("Annuler").'" />';
?>
    </form></td></tr>
    </table>    
  <?php
          processFile($uploadfile);
    } 
    else {
        echo _("Echec")." :<br/>";
    }
}

if (isset($_POST['path']) && isset($_POST['liv_location_id']) && isset($_POST['liv_genre_id']) ) {
  processFile($_POST['path'], true);
}

include_once("includes/footer.inc");

?>

